<?php
namespace app\app\model;
use think\Model;
class Questions extends Model
{
    public function saveUserAnswer(array $user_answer)
    {
        $question_list = db('questions')->where('id',$user_answer['questions_id'])->value('questions');
        $question_list = json_decode($question_list,true);
        $user_answer['score'] = 0;
        foreach ($user_answer['questions'] as $ak => &$av){
            foreach ($question_list as $qk => $qv){
                if ($av['question_id'] == $qv['question_id']){
                    switch ($av['type']){
                        case '1':
                            if ($qv['true_answer'] == $av['answer']){
                                $av['iftrue'] = true;
                                $user_answer['score'] += $qv['score'];
                                continue;
                            }
                            
                            break;
                        case '2':
                            $qv['true_answer'] = explode('&', $qv['true_answer']);
                            sort($qv['true_answer']);
                            $av['answer'] = explode('&', $av['answer']);
                            sort($av['answer']);
                            if ($qv['true_answer'] == $av['answer']){
                                $av['iftrue'] = true;
                                $user_answer['score'] += $qv['score'];
                                $av['answer'] = implode('&', $av['answer']);
                                continue;
                            }
                            $av['answer'] = implode('&', $av['answer']);
                            break;
                        case '3':
                            $qv['true_answer'] = explode('&', $qv['true_answer']);
                            $count = count($qv['true_answer']);
                            $true = 0;
                            foreach ($qv['true_answer'] as $qtak => $qtav){
                                if (strpos($av['answer'], $qtav) !== false){
                                    $true++;
                                }
                            }
                            if ($true == $count){
                                $av['iftrue'] = true;
                                $user_answer['score'] += $qv['score'];
                                continue;
                            }else {
                                $av['iftrue'] = false;
                            }
                            break;
                    }
                    
                    
                    
                }
             
            }
        }
        $user_answer['created'] = time();
        $user_answer['questions'] = json_encode($user_answer['questions']);
        $questionslog = new Questionslog;
        $questionslog_id = $questionslog->save($user_answer);
        return $questionslog_id;
    }
}